package cn.wolfcode.p2p.mgrsite.job;

import cn.wolfcode.p2p.base.util.Constants;
import cn.wolfcode.p2p.bussness.domain.BidRequest;
import cn.wolfcode.p2p.bussness.service.IBidRequestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * Created by wolfcode-lanxw
 */
@Component
public class BidRequestScheduledJob implements ApplicationListener<ContextRefreshedEvent> {
    @Autowired
    private IBidRequestService bidRequestService;
    //创建一个线程安全的集合对象
    private ConcurrentLinkedQueue<BidRequest> bidRequestQueue = new ConcurrentLinkedQueue<BidRequest>();
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        //实现监听器接口,启动服务器的时候就可以查询
        queryBidRequestListScheduledJob();
    }
    @Scheduled(cron = "0 0 0/1 * * ?")
    public void queryBidRequestListScheduledJob(){
        //查询最近一小时待发布的借款,放入内存中
        List<BidRequest> bidRequestList = bidRequestService.queryPendingBidRequest();
        for(BidRequest br:bidRequestList){
            bidRequestQueue.add(br);
        }
        System.out.println("每小时的定时任务查询待发布的标集合:"+bidRequestList);
    }
    @Scheduled(cron = "0 0/1 * * * ?")
    public void publicBidRequestListScheduledJob(){
        System.out.println("开始执行任务-->"+bidRequestQueue);
        Iterator<BidRequest> iterator = bidRequestQueue.iterator();
        BidRequest br = null;
        while (iterator.hasNext()){
            br = iterator.next();
            if((new Date().getTime()-br.getPublishTime().getTime())>=0){
                //到时间,更改状态
                br.setBidRequestState(Constants.BIDREQUEST_STATE_BIDDING);
                bidRequestQueue.remove(br);//已经查询出来的数据要删除掉,就不会再次被扫描
                bidRequestService.update(br);
            }
        }
        System.out.println("结束执行任务-->"+bidRequestQueue);
    }
}
